<template>
  <div>

    <el-card class="box-card" style="margin: 10px">
      <el-form :inline="true" :model="patientform" size="mini" :rules="rules">
        <el-row>
          <el-col>
            <el-form-item label="身份证号:" prop="idCard">
              <el-input v-model="patientform.idCard" placeholder="请输入患者身份证" />
            </el-form-item>
            <el-form-item label="患者姓名:" prop="patientName">
              <el-input v-model="patientform.patientName" placeholder="请输入患者姓名" />
            </el-form-item>
            <el-form-item label="患者电话:" prop="tel">
              <el-input v-model="patientform.tel" placeholder="请输入患者电话" />
            </el-form-item>
            <template slot-scope="scope">
              <dict-tag :options="dict.type.his_doctor_sex" v-model="patientform.gender"/>
            </template>
            <el-form-item label="出生日期:" prop="patientDate">
              <el-date-picker clearable v-model="patientform.patientDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择出生日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="性别: " prop="gender">
              <dict-tag :options="dict.type.his_doctor_sex" :value="patientform.gender"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="margin: 5px" :span="24">
            <el-form-item label="患者年龄" prop="age">
              <el-input v-model="patientform.age" placeholder="请输入患者年龄" />
            </el-form-item>
            <el-form-item label="地址信息" prop="address">
              <el-input v-model="patientform.address" placeholder="请输入地址信息" />
            </el-form-item>
            <el-form-item>
              <el-button type="warning" icon="el-icon-search" @click="add">选择我的患者</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
    </el-card>
    <el-card class="box-card" style="margin: 10px">
      <div>
        <el-form :model="queryParams1" :inline="true" size="mini" ref="queryParams1">
          <el-form-item label="所属科室" prop="deptId">
        <el-select
          v-model="queryParams1.deptId"
          placeholder="请选择科室"
          clearable
          @change="handleQuery"
        >
          <el-option
            label="全部科室"
            :value="null"
          />
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
          <el-form-item label=" 挂号日期" prop="schedDate">
            <el-date-picker type="date" placeholder="挂号日期" v-model="queryParams1.schedDate"
              :default-value="timeDefaultShow" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getNewSheduleList">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="newscheduleList" border style="width: 100%" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column label="科室" align="center" prop="deptId">
        <template slot-scope="scope">
          {{
            (deptOptions.find(item => item.deptId === scope.row.deptId) &&
            deptOptions.find(item => item.deptId === scope.row.deptId).deptName)
            || '未知科室'
          }}
        </template>
      </el-table-column>
        <el-table-column prop="doctName" label="医生姓名" align="center">
        </el-table-column>
        <el-table-column prop="doctSex"  label="医生性别" align="center">
          <template slot-scope="scope">
          <dict-tag :options="dict.type.his_doctor_sex" :value="scope.row.doctSex" />
        </template>
        </el-table-column>
        <el-table-column prop="doctLevel" label="医生职称" align="center">
          <template slot-scope="scope">
          <dict-tag :options="dict.type.his_docter_level" :value="scope.row.doctLevel" />
        </template>
        </el-table-column>
        <el-table-column prop="doctEducationBg" label="医生学历" align="center">
          <template slot-scope="scope">
          <dict-tag :options="dict.type.his_docter_bg" :value="scope.row.doctEducationBg" />
        </template>
        </el-table-column>
        <el-table-column label="挂号日期" align="center" prop="schedDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.schedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="addReg(scope.row)"
          >挂号</el-button>
        </template>
      </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

     <!-- 患者选择弹窗 -->
  <el-dialog
    title="我的患者列表"
    :visible.sync="dialogVisible"
    width="80%"
    append-to-body
    class="custom-dialog"
  >
    <el-card class="box-card" style="margin: 10px">
      <el-table
        :data="patientList"
        border
        highlight-current-row
        @current-change="handlePatientSelect"
        v-loading="patientLoading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        ref="patientTable"
      >
      <el-table-column type="selection" width="55" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="患者电话" align="center" prop="tel" />
      <el-table-column label="患者身份证" align="center" prop="idCard" />
      <el-table-column label="患者年龄" align="center" prop="age" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.his_doctor_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="地址信息" align="center" prop="address" />
      <el-table-column label="出生日期" align="center" prop="patientDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.patientDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      </el-table>


    </el-card>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirmSelection">确 定</el-button>
    </div>
  </el-dialog>


      <!-- 挂号确认弹窗 -->
      <el-dialog
      title="挂号确认"
      :visible.sync="confirmDialogVisible"
      width="40%"
      append-to-body
      class="custom-dialog"
    >
      <p>你所挂号的科室为：{{ confirmForm.deptName }}</p>
      <p>医生为：{{ confirmForm.doctName }}</p>


      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRegistration">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import {addRegistration,listRegable } from "@/api/his/registration";
  import { listNewschedule, getNewschedule, delNewschedule, addNewschedule, updateNewschedule } from "@/api/his/newschedule";
  import { listPatient, getPatient, delPatient, addPatient, updatePatient } from "@/api/his/patient";
  import { listNewregistration, getNewregistration, delNewregistration, addNewregistration, updateNewregistration } from "@/api/his/newregistration";
  import { listDept} from "@/api/his/dept";
  import { addDoctor, delDoctor, getDoctor, listDoctor, updateDoctor } from "@/api/his/doctor";
export default {
  dicts: ['his_doctor_sex','his_department','his_docter_bg', 'his_is_orderwork', 'his_docter_level'],
  data() {
    return {
      params :null,
         // 科室选项
         deptOptions: [],
      dialogVisible: false,
      patientLoading: false,
       // 患者表格数据
       patientList: [],
           // newschedule表格数据
      newscheduleList: [],
      patientTotal: 0,
      currentPatient: null,
    //是否需要病历本，默认不需要
      checked: false,
    //挂号费用
      regCost:null,
      doctorMap: new Map(),
    //禁用今日之前的日期
      pickerOptions: {
          disabledDate(date) {
            let curDate = new Date();
            return date<new Date(curDate.getTime() - 24*60*60*1000);
          }},
     // 总条数
      total: 0,
      timeDefaultShow :"",
      //级联下拉框初始化数据
      depts:[],
      //新增患者表单数据
      patientform: {},
      // 查询可挂号列表参数
        queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        tel: null,
        idCard: null,
        age: null,
        gender: null,
        address: null,
        patientDate: null,
        allergy: null,
        patienUsername: null,
      },
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        doctId: null,
        schedDate: null,
        timePeriod: null,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 100,
      },
      //增加挂号参数
      addRegParams:{
        registrationType:null,
        registrationPatientId:null,
        registrationSchedule:null,
      },
      idCard:"",//用于加载身份证
      // 表单校验
      rules: {
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "患者电话不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "患者身份证不能为空", trigger: "blur" }
        ],
      },
      //可挂号表格数据
      dataList:[],
      confirmDialogVisible: false,
      confirmForm: {
        patientName: '',
        deptName: '',
        doctName: '',
        doctLevel: '',
        schedDate: '',
      },
      
    };
  },
  created() {
    listDoctor(this.queryParams2).then(response => {
      response.rows.forEach(doctor => {
      this.doctorMap.set(doctor.doctId, doctor);
      });
    }).catch(error => {
      this.$message.error('获取医生信息失败: ' + error.message);
    });
      this.queryParams.patienUsername = this.$store.state.user.name;
      this.getList();
      //初始化查询日期为今天
      this.queryParams1.schedDate = this.getCurrentDate();
      this.getNewSheduleList()
      listDept().then(response => {
        this.deptOptions = response.rows;
      });
     
    },
  methods: {
     // 获取当前日期（格式：YYYY-MM-DD）
  getCurrentDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
     /** 查询newschedule列表 */
     getNewSheduleList() {
      this.loading = true;
      listNewschedule(this.queryParams1).then(response => {
        this.newscheduleList = response.rows;
        
          // 匹配医生信息
      this.newscheduleList.forEach(sched => {
        console.log(this.doctorMap)
        const doctor = this.doctorMap.get(sched.doctId);
        console.log(doctor)
        if (doctor) {
          sched.doctSex = doctor.doctSex;
          sched.doctEducationBg = doctor.doctEducationBg;
          sched.doctLevel = doctor.doctLevel;
        }
      });
      console.log(this.newscheduleList)
      this.total = response.total;
      this.loading = false;
   
      });
    },


  // 选择患者行
  handlePatientSelect(currentRow) {
    this.currentPatient = currentRow;
  },

  // 处理选择框变化
  handleSelectionChange(selection) {
    if (selection.length > 0) {
      this.currentPatient = selection[0];
    } else {
      this.currentPatient = null;
    }
  },

  // 确认选择
  confirmSelection() {
    if (!this.currentPatient) {
      this.$message.warning('请先选择患者');
      return;
    }
    // 将选中的患者数据赋值给 patientform
    this.patientform = { ...this.currentPatient };
    this.dialogVisible = false;
  },

    handleChange(value) {
      console.log(value);
    },

    //选择我的患者
    add() {
      this.dialogVisible = true
      listPatient(this.queryParams).then(response => {
        this.patientList = response.rows;

      });
    },
    /** 搜索按钮操作 */
     handleQuery() {
        this.queryParams1.pageNum = 1;
        console.log("搜索的参数",this.queryParams)
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryParams");
         this.handleQuery();
        console.log("重置后的参数",this.queryParams)
      },
      getList() {//获取可挂号列表
        listRegable(this.queryParams).then(r => {
                  if (r.code == 200 ) {
                      this.dataList = r.rows;
                      this.total = r.total;
                  }
              });
          },
      //表格单选
     handleCurrentChange(val) {
        this.addRegParams.registrationSchedule=val.scheduleId;
        if(this.checked&&val.scheduleType=="门诊"){
            this.addRegParams.registrationType=2
            this.regCost=8
        }else if(this.checked&&val.scheduleType=="急诊"){
          this.addRegParams.registrationType=4
          this.regCost=12
        }else if(!this.checked&&val.scheduleType=="急诊"){
          this.addRegParams.registrationType=3
          this.regCost=10
        }else if(!this.checked&&val.scheduleType=="门诊"){
          this.addRegParams.registrationType=1
          this.regCost=6
        };
        console.log(this.addRegParams)
      },
      //挂号按钮操作
      addReg(row){
        if(!this.patientform.patientId){
          this.$message.warning('请先选择患者');
          return;
        }
            // 设置确认表单信息
        this.confirmForm.patientName = this.patientform.patientName;
        this.confirmForm.deptName = this.deptOptions.find(dept => dept.deptId === row.deptId)?.deptName || '未知科室';
        this.confirmForm.doctName = row.doctName;
        this.confirmForm.doctLevel = row.doctLevel;
        this.confirmForm.schedDate = this.parseTime(row.schedDate, '{y}-{m}-{d}');
        this.confirmDialogVisible = true;

        this.params = {
            registrationPatientId : this.patientform.patientId,
            registrationPatientName : this.patientform.patientName,
            registrationSchedule : row.schedDate,
            registrationDeptId : row.deptId,
            registrationDoctorId : row.doctId,
            registrationDoctorName : row.doctName
          }

    
      },
      confirmRegistration() {
        // const params = {
        //     registrationPatientId : this.patientform.patientId,
        //     registrationPatientName : this.patientform.patientName,
        //     registrationSchedule : row.schedDate,
        //     registrationDeptId : row.deptId,
        //     registrationDoctorId : row.doctId,
        //     registrationDoctorName : row.doctName
        //   }
          addNewregistration(this.params).then(r => {
            if (r.code == 200 ) {
              this.$message.success("挂号成功");
              this.confirmDialogVisible = false;
              this.getList();
            }
          });
    },

  },


}
</script>
